<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			html,
		        body,
		        #app {
		            height: 100%;
		            margin: 0;
		            padding: 0;
		        }
		        .operate {
		            position: absolute;
		            bottom: 0;
		            padding-bottom: 20px;
		            text-align: center;
		            width: 100%;
		        }
		        .operate button {
		            font-size: 14px;
		            color: #fff;
		            height: 42px;
		            border-radius: 21px;
		            padding: 0 38px;
		            background:rgba(45,153,255,1);
		            outline: none !important;
		            border: none;
		            display: inline-flex;
		            align-items: center;
		            margin-right: 10px;
		        }
		        .operate img {
		            width: 15px;
		            height: 15px;
		            margin-right: 10px;
		        }
		        #info {
		            position: absolute;
		            width: 580px;
		            height: 107px;
		            background: rgba(84, 147, 255, 1);
		            border-radius: 0px 0px 8px 8px;
		            opacity: 0.8;
		            left: 0;
		            right: 0;
		            top: 0;
		            margin: auto;
		            z-index: 100;
		            padding: 10px 20px;
		            color: #fff;
		        }
		        .top-info {
		            display: flex;
		            align-items: center;
		        }
		        #direction-img {
		            height: 40px;
		        }
		        #message {
		            font-size: 24px;
		            margin-left: 15px;
		        }
		        #rest-message {
		            margin-top: 20px;
		            font-size: 16px;
		        }
		    </style>
		<link rel="stylesheet" href="./palmap-map-v5.5.0.css">
		<script src="./palmap-map-v5.5.0.js"></script>
	</head>
	<body>
		<!-- <div id="app" style="height: 900px"></div> -->

		<div id="info" style="display: none;">
			<div class="top-info">
				<img id="direction-img" src="./direction/bottom-elevator.png" alt="">
				<span id="message"></span>
			</div>
			<div id="rest-message"></div>
		</div>
		<div id="app">

		</div>
		<div class="operate">
			<button id="sim-btn" onclick="simulateNavigate()" style="display: none;">
				<img src="assets/simulate.png" alt="">
				模拟导航
			</button>
			<button id="recovery-btn" onclick="recoveryNavigate()" style="display: none">
				恢复导航(5s)
			</button>
			<button id="exit-btn" onclick="exitSimulate()" style="display: none;">
				<img src="assets/exit.png" alt="">
				退出导航
			</button>
		</div>
	</body>
	<script type="application/javascript">
		const map = new NGR.Map({
			appKey: '707e8cdd6fb2415a9206f8045728e1df',
			buildingId: '012D01'
		});
		map.init('app', './style.json');


		startP = {
			x: 13516028.122125603,
			y: 3661158.819978341
		};

		endP = {
			x: 13516095.762464348,
			y: 3661289.5701358584
		};

		//缩放
		map.jumpTo({
			zoom: 18
		});

		map.jumpTo({
			center: {
				x: 13516078.100866362,
				y: 3661208.548941049
			}
		});

		const naviMng = new NGR.Navigate({
			lineImage: './assets/ic_line.png',
			lineWidth: 5,
			markerConfig: {
				start: {
					type: 'layer',
					anchor: 'bottom',
					size: 0.5,
					url: './assets/marker/ic_start.png'
				},
				end: {
					type: 'layer',
					anchor: 'bottom',
					size: 0.5,
					url: './assets/marker/ic_end.png'
				},
				sim: {
					type: 'overlay',
					url: './assets/marker.png',
					anchor: 'center',
					plane: true,
					size: [45, 45],
				}
			},
			simSpeed: 5,
			strategies: ['shortest']
		});
		naviMng.addTo(map);

		var msgIdStart = 1;
		naviMng.on('navigatingInfo', (info) => {

			var p = naviMng._dynamicMng._ctrCoordinate;
			var mark = false;
			if (mark) {
				const img = new Image();
				img.src = './assets/pick.png';
				img.style.width = '20px'
				img.style.height = '20px';
				// 创建 marker 实例
				const marker = new NGR.Marker(img);
				// marker.title = i;
				marker.setPosition(map.currentFloor, p);

				marker.addTo(map);
			}

			var msgId = msgIdStart;
			msgIdStart = msgIdStart + 1;
			console.log("开始向信标发送信号, msgId = " + msgId)

			label = {
				id: labelId,
				x: p.x,
				y: p.y
			};
			mock(distinct(p.x, p.y), msgId);
		});


		var x = [13516085.802019743, 13516076.892079443, 13516067.753679136, 13516058.386818819, 13516047.649198458,
			13516038.967718165, 13516055.873758735, 13516069.124439182, 13516077.805919474, 13516089.914299881,
			13516101.337300267, 13516110.247240566, 13516116.415660774, 13516121.670240952
		]
		var y = [3661256.7869963837, 3661242.850936896, 3661229.1433374, 3661214.978817921, 3661199.9004584756,
			3661188.9343788787, 3661166.088379719, 3661175.4552393747, 3661188.9343788787, 3661203.3273583497,
			3661217.7203378202, 3661233.255617249, 3661250.1616566274, 3661265.9253960475
		]
		//加载完成回调
		map.on('loaded', async () => {
			console.log('地图加载完成');

			for (var i = 0; i < x.length; i++) {
				const img = new Image();
				img.src = './assets/pick.png';
				img.style.width = '20px'
				img.style.height = '20px';
				img.title = i + "";
				// 创建 marker 实例
				const marker = new NGR.Marker(img);
				// marker.title = i;
				marker.setPosition(map.currentFloor, {
					x: x[i],
					y: y[i]
				});

				marker.addTo(map);

				naviMng.setStartMarker(map.currentFloor, {
					x: startP.x,
					y: startP.y
				});
				naviMng.setEndMarker(map.currentFloor, {
					x: endP.x,
					y: endP.y
				});
				await naviMng.initNavi();
				naviMng.fitNaviLine();
				naviMng.simulateNavigate();
			}
		});


		function distinct(xaxis, yaxis) {
			var d = [];
			for (var i = 0; i < x.length; i++)
				d[i] = {
					id: i,
					x: x[i],
					y: y[i],
					dis: Math.sqrt((xaxis - x[i]) * (xaxis - x[i]) + (yaxis - y[i]) * (yaxis - y[i]))
				};

			d.sort(sortByDis);

			console.log("信标与标签的距离排序：")
			console.log(d);

			return d;
		}

		function sortByDis(a, b) {
			return a.dis - b.dis;
		}


		// setTimeout(function(){alert("Hello")},3000);

		function randomNum(minNum, maxNum) {
			switch (arguments.length) {
				case 1:
					return parseInt(Math.random() * minNum + 1, 10);
					break;
				case 2:
					return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
					break;
				default:
					return 0;
					break;
			}
		}

		function mock(d, msgId) {
			console.log("开始模拟信标向服务端发送消息...")
			var sendNum = randomNum(3, 10);
			console.log("接收到标签信号的信标数为：" + sendNum);
			selectDSend(sendNum, d, msgId);
		}

		function selectDSend(n, d, msgId) {
			selected = [];
			ddd = d.slice(0, n);
			for (var i = 0; i < n; i++) {
				var index = randomNum(0, ddd.length - 1);
				var rssi = getRssi(ddd[index]);
				send(ddd[index].id, rssi, msgId);
				ddd.splice(index, 1);
				setTimeout(function() {}, 500);
			}
		}
		var label;
		var labelId = "label-001";

		rssiArr = [-54, -56, -55.34, -57];

		function getRssi(beacon) {
			return -(Math.log10(beacon.dis * 10 * 2) + 54);
		}

		function send(beaconId, rssi, msgId) {
			console.log(beaconId + "开始向服务端发送数据 RSSI = " + rssi);
			var url = "http://localhost:8080/beacon/mock/msg?id=" + beaconId + "&rssi=" + rssi + "&msgId=" + msgId + "&labelId=" +
				label.id;

			var xhr = new XMLHttpRequest();
			xhr.open('GET', url, true);
			xhr.onreadystatechange = function() {
				console.log(beaconId + "发送数据成功");
			};
			xhr.send();
		}

		function markLine(coordinatesArr) {
			console.log(coordinatesArr);
			const line = new NGR.LineLayer({
				visible: true,
				lineWidth: 10,
				lineColor: '#ff3e96',
				// 线图片
				// lineImage: 'marker/ic_line.png',
			});

			line.setFeatures([{
				type: 'Feature',
				geometry: {
					type: 'LineString',
					coordinates: coordinatesArr,
				},
			}]);

			map.addLayer(line);
			line.setFloorId(map.currentFloor);
			map.updateLayer(line);
		}

		var resNum = -1;
		var lastLength = 0;
		setInterval(function() {
			if (resNum === -100) {
				return;
			}
			var url = "http://localhost:8080/label/list?labelId=" + labelId;

			var xhr = new XMLHttpRequest();
			xhr.open('GET', url, true);
			xhr.onreadystatechange = function() {
				if (xhr.readyState !== 4 || xhr.responseText === '' || xhr.responseText === null) {
					return;
				}
				var labelResArr = JSON.parse(xhr.responseText);

				if (lastLength === labelResArr.length) {
					resNum = resNum - 1;
				} else {
					resNum = -1;
				}
				lastLength = labelResArr.length;

				if (resNum < -20) {
					var coordinatesArr = [];
					for (var i = 0; i < labelResArr.length; i++) {
						var labelRes = labelResArr[i];
						var arrT = [];
						arrT[0] = labelRes.x;
						arrT[1] = labelRes.y;
						coordinatesArr[i] = arrT;
					}
					markLine(coordinatesArr);
					resNum = -100;
					return;
				}

				for (var i = 0; i < labelResArr.length; i++) {
					var labelRes = labelResArr[i];
					const img = new Image();
					img.src = './assets/marker/ic_pick.png';
					img.style.width = '20px'
					img.style.height = '20px';
					const marker = new NGR.Marker(img);
					marker.setPosition(map.currentFloor, {
						x: labelRes.x,
						y: labelRes.y
					});
					marker.addTo(map);
				}

			};
			xhr.send();
		}, 500);
	</script>
</html>
